package fa7.socialcode.dao.hibernate;

import java.util.List;
import java.util.StringTokenizer;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import fa7.socialcode.dao.ConteudoDao;
import fa7.socialcode.model.Conteudo;

/**
 * 
 * @author Paulo Sergio Girao
 * 
 */
@Repository(value = "conteudoDao")
public class ConteudoDaoHibernate implements ConteudoDao {

  HibernateTemplate hibernateTemplate;
  // Somente para log
  Log logger = LogFactory.getLog(ConteudoDaoHibernate.class);

  @Autowired
  public ConteudoDaoHibernate(SessionFactory sessionFactory) {
    this.hibernateTemplate = new HibernateTemplate(sessionFactory);
  }

  @Override
  public Conteudo findConteudo(Long exampleId) {
    Conteudo conteudo = (Conteudo) hibernateTemplate.get(Conteudo.class,
        exampleId);
    if (conteudo == null) {
      throw new ObjectRetrievalFailureException(Conteudo.class, exampleId);
    }
    return conteudo;
  }

  @Override
  public List findConteudos() {

    return hibernateTemplate.find("From Conteudo");
  }
  
  @Override
  public List findConteudosByUsuarioId(Long usuarioId) {

    return hibernateTemplate.find("from Conteudo c where c.usuario.id = ?", usuarioId);
  }

  @Override
  public void removeConteudo(Long exampleId) {
    hibernateTemplate.delete(findConteudo(exampleId));

  }

  @Override
  public void removeConteudo(Conteudo conteudo) {
    hibernateTemplate.delete(findConteudo(conteudo.getId()));
  }

  @Override
  public void saveConteudo(Conteudo conteudo) {
    hibernateTemplate.merge(conteudo);
    if (logger.isDebugEnabled()) {
      logger.debug("conteudoId set to: " + conteudo.getId());
    }

  }
  @Override
  public List pesquisarConteudo(String busca) {

    String where = "";

    StringTokenizer buscaArray = new StringTokenizer(busca, " ");

    while (buscaArray.hasMoreTokens()) {

      where += "titulo like '%" + buscaArray.nextToken() + "%'";

      if (buscaArray.hasMoreTokens()) {
        where += " AND ";
      }

    }

    return hibernateTemplate.find("from Conteudo WHERE " + where);

  }

}
